package com.wang.gulimall.auth.controller;


import com.alibaba.fastjson.TypeReference;
import com.wang.common.constant.AuthServerConstant;
import com.wang.common.exception.BizCodeEnum;
import com.wang.common.utils.R;
import com.wang.common.vo.MemberResponseVo;
import com.wang.gulimall.auth.feign.MemberFeignService;
import com.wang.gulimall.auth.feign.ThirdPartFeignService;
import com.wang.gulimall.auth.vo.UserLoginVo;
import com.wang.gulimall.auth.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.wang.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * @Auther: wangliuyang
 * @Date: 2021/5/2 15:11
 * @Description:
 */
@Controller
@Slf4j
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

//    //登录界面
//    @GetMapping(value = {"/", "/login.html"})
//    public String loginPage() {
//        return "login";
//    }

    //注册界面
    @GetMapping(value = {"/reg.html"})
    public String regPage() {
        return "reg";
    }


    //提供给别的服务进行调用
    //问题1 防止接口恶意被刷新
    //问题2 验证码的校验问题
    @ResponseBody //将java对象转换为json对象将controller的方法返回的对象通过适当的转换器转换为指定的格式
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long lastTime = Long.parseLong(redisCode.split("_")[1]);
            //获取过于频繁请稍后再试
            if (System.currentTimeMillis() - lastTime < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }

        String code = String.valueOf(Math.random()).substring(2, 8);
        thirdPartFeignService.sendCode(phone, code);
        log.info("发送短信请求");
        code += "_" + System.currentTimeMillis();
        //sms:code:18852899151+验证码
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code, 60000000, TimeUnit.MINUTES);
        return R.ok();
    }

    /**
     * TODO: 重定向携带数据【request域失效】：利用session原理，将数据放在session中。
     * TODO: 只要跳转到下一个页面取出这个数据以后，session里面的数据就会删掉
     * TODO: 分布式下session问题
     * RedirectAttributes：重定向也可以保留数据，不会丢失
     * 用户注册
     * @return
     */
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vos,
                           BindingResult result,
                           RedirectAttributes attributes) {
        //如果有错误回到注册页面
        if (result.hasErrors()) {
            Map<String, String> errors = new HashMap<>();
            ;
            //1.1 如果校验不通过，则封装校验结果
            result.getFieldErrors().forEach(item -> {
                // 获取错误的属性名和错误信息
                errors.put(item.getField(), item.getDefaultMessage());
                //1.2 将错误信息封装到session中
                attributes.addFlashAttribute("errors", errors);
            });
            //1.2 重定向到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
            // 1、return "reg"; 请求转发【使用Model共享数据】【异常：，405 POST not support】
            // 2、"redirect:http:/reg.html"重定向【使用RedirectAttributes共享数据】【bug：会以ip+port来重定向】
            // 3、redirect:http://auth.gulimall.com/reg.html重定向【使用RedirectAttributes共享数据】
        }

        //1、效验验证码 获取前台验证码
        String code = vos.getCode();
        //获取存入Redis里的验证码 547270_1622636671793_1622636675905
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            log.info("redis数据不为空");
            // 判断验证码是否正确 取出第一段验证码  令牌机制
            if (code.equals(redisCode.split("_")[0])) {
                //删除redis缓存数据
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
                //验证码通过，真正注册，调用远程服务进行注册【会员服务】
                R callServiceCode = memberFeignService.register(vos);
                if (callServiceCode.getCode() == 0) {
                    log.info("调用会员服务成功");
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    log.info("调用会员服务失败");
                    Map<String, String> errors = new HashMap<>();
                    errors.put("code", callServiceCode.getData(new TypeReference<String>() {
                    }));

                    attributes.addFlashAttribute("errors", errors);
                    //调用会员服务失败
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            } else {//错误
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            //验证码过期
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码过期");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    //登录请求功能
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {
        //调用member远程会员服务 vo UserLoginVo(loginacct=abc123, password=1510huyue)
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            //调用成功
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {});
            session.setAttribute(LOGIN_USER,data);
            //Object dataTest = session.getAttribute("data");
            //返回商城主界面
            return "redirect:http://gulimall.com";
        } else {
            //调用失败
            String msg = (String) login.get("msg");
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", msg);
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    //用户登录界面按钮
    //判断session是否有loginUser，没有就跳转登录页面，有就跳转首页
    @GetMapping(value = {"/", "/login.html"})
    public String loginPage(HttpSession session) {
        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute(LOGIN_USER);
        //如果用户没登录那就跳转到登录页面
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }
    }

    @GetMapping(value = "/loguot.html")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(LOGIN_USER);
        request.getSession().invalidate();
        return "redirect:http://gulimall.com";
    }
}
